package com.hmall.search.listener;

import com.alibaba.fastjson.JSON;
import com.hmall.clients.ItemClient;
import com.hmall.pojo.Item;
import com.hmall.search.common.ESConstant;
import com.hmall.search.common.MQConstant;
import com.hmall.search.pojo.ItemDoc;
import lombok.SneakyThrows;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @Author Mingxi Guo
 * @Create 2022-07-16 22:27
 * @Email guomingxi2018@163.cm
 */

@Component
public class MQListener {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ItemClient itemClient;

    /**
     * 监听有插入操作时，向es插入数据
     *
     * @param id
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(name = MQConstant.MQ_EXCHANGE),
            value = @Queue(name = MQConstant.MQ_INSERT_QUEUE, durable = "true", autoDelete = "false"),
            key = MQConstant.INSERT_KEY
    ))
    public void listenDBInsert(Long id) {
        Item item = itemClient.getById(id);

        if (Objects.isNull(item)) {
            throw new RuntimeException("数据库插入不成功");
        }
        ItemDoc itemDoc = new ItemDoc(item);
        String json = JSON.toJSONString(itemDoc);
        IndexRequest indexRequest = new IndexRequest(ESConstant.INDEX_NAME);
        indexRequest.source(json, XContentType.JSON).id(itemDoc.getId().toString());
        restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);

    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstant.MQ_DELETE_QUEUE, durable = "true", autoDelete = "false"),
            exchange = @Exchange(name = MQConstant.MQ_EXCHANGE),
            key = MQConstant.DELETE_KEY
    ))
    public void ListenDBDel(Long id) {
        DeleteRequest deleteRequest = new DeleteRequest(ESConstant.INDEX_NAME);
        deleteRequest.id(id.toString());
        restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);

    }
}
